package com.yvan.codeslave;

import com.intellij.util.ExceptionUtil;
import com.yvan.codeslave.snippet.Idea;
import org.beetl.core.ConsoleErrorHandler;
import org.beetl.core.Resource;
import org.beetl.core.ResourceLoader;
import org.beetl.core.exception.BeetlException;
import org.beetl.core.exception.ErrorInfo;

import java.io.IOException;
import java.io.Writer;

public class IdeaErrorHandle extends ConsoleErrorHandler {
    @Override
    public void processExcption(BeetlException ex, Writer writer) {
        super.processExcption(ex, writer);

        ErrorInfo error = new ErrorInfo(ex);
        StringBuilder sb = new StringBuilder(">>").append(this.getDateTime()).append(":");
        sb.append(error.getType());
        sb.append(":");
        sb.append(error.getErrorTokenText());
        sb.append("位于");
        sb.append(error.getErrorTokenLine());
        sb.append("行资源:");
        sb.append(getResourceName(ex.resource.getId()));
        sb.append("\n");

        String content = null;
        ResourceLoader resLoader = ex.gt.getResourceLoader();
        try {
            Resource res = resLoader.getResource(ex.resource.getId());
            int[] range = this.getRange(error.getErrorTokenLine());
            content = res.getContent(range[0], range[1]);
            if (content != null) {
                String[] strs = content.split(ex.cr);
                int lineNumber = range[0];
                for (int i = 0; i < strs.length; i++) {
                    sb.append(lineNumber);
                    sb.append("|");
                    sb.append(strs[i]);
                    sb.append("\n");
                    lineNumber++;
                }

            }
        } catch (IOException e) {
            ExceptionUtil.rethrow(e);
        }
        Idea.notifyError(sb.toString());
    }
}
